import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface iCloudFile {
  id: string
  name: string
  type: 'file' | 'folder'
  size?: number
  modifiedTime: Date
  icon: string
  isShared?: boolean
  isFavorite?: boolean
}

export const useICloudStore = defineStore('icloud', () => {
  // 存储数据
  const files = ref<iCloudFile[]>([
    { id: '1', name: '文稿', type: 'folder', modifiedTime: new Date('2025-01-15'), icon: '📄', isFavorite: true },
    { id: '2', name: '桌面', type: 'folder', modifiedTime: new Date('2025-01-20'), icon: '🖥️' },
    { id: '3', name: '照片', type: 'folder', modifiedTime: new Date('2025-01-18'), icon: '🖼️', isFavorite: true },
    { id: '4', name: '项目报告.pdf', type: 'file', size: 2048000, modifiedTime: new Date('2025-01-22'), icon: '📄' },
    { id: '5', name: '设计稿.sketch', type: 'file', size: 5120000, modifiedTime: new Date('2025-01-21'), icon: '🎨' },
    { id: '6', name: '音乐', type: 'folder', modifiedTime: new Date('2025-01-10'), icon: '🎵' },
    { id: '7', name: '视频', type: 'folder', modifiedTime: new Date('2025-01-12'), icon: '🎬' },
    { id: '8', name: '演示文稿.keynote', type: 'file', size: 8192000, modifiedTime: new Date('2025-01-23'), icon: '📊', isShared: true },
  ])

  // 当前路径
  const currentPath = ref<string[]>(['iCloud Drive'])
  
  // 视图模式
  const viewMode = ref<'grid' | 'list'>('grid')
  
  // 存储信息
  const storageUsed = ref(28.5) // GB
  const storageTotal = ref(50) // GB
  
  // 选中的文件
  const selectedFiles = ref<string[]>([])
  
  // 搜索关键词
  const searchQuery = ref('')

  // 添加文件/文件夹
  function addFile(file: Omit<iCloudFile, 'id'>) {
    const newFile: iCloudFile = {
      ...file,
      id: Date.now().toString(),
    }
    files.value.unshift(newFile)
    saveToStorage()
  }

  // 删除文件
  function deleteFile(fileId: string) {
    files.value = files.value.filter(f => f.id !== fileId)
    selectedFiles.value = selectedFiles.value.filter(id => id !== fileId)
    saveToStorage()
  }

  // 重命名文件
  function renameFile(fileId: string, newName: string) {
    const file = files.value.find(f => f.id === fileId)
    if (file) {
      file.name = newName
      saveToStorage()
    }
  }

  // 切换收藏
  function toggleFavorite(fileId: string) {
    const file = files.value.find(f => f.id === fileId)
    if (file) {
      file.isFavorite = !file.isFavorite
      saveToStorage()
    }
  }

  // 切换分享
  function toggleShare(fileId: string) {
    const file = files.value.find(f => f.id === fileId)
    if (file) {
      file.isShared = !file.isShared
      saveToStorage()
    }
  }

  // 切换视图模式
  function setViewMode(mode: 'grid' | 'list') {
    viewMode.value = mode
    saveToStorage()
  }

  // 选择文件
  function selectFile(fileId: string) {
    if (!selectedFiles.value.includes(fileId)) {
      selectedFiles.value.push(fileId)
    }
  }

  // 取消选择
  function deselectFile(fileId: string) {
    selectedFiles.value = selectedFiles.value.filter(id => id !== fileId)
  }

  // 清空选择
  function clearSelection() {
    selectedFiles.value = []
  }

  // 格式化文件大小
  function formatFileSize(bytes?: number): string {
    if (!bytes) return '-'
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
    if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
    return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
  }

  // 保存到 localStorage
  function saveToStorage() {
    try {
      const data = {
        files: files.value,
        viewMode: viewMode.value,
        storageUsed: storageUsed.value,
        storageTotal: storageTotal.value,
      }
      localStorage.setItem('vue-desktop:icloud', JSON.stringify(data))
    } catch (_) {
      // 忽略错误
    }
  }

  // 从 localStorage 加载
  function loadFromStorage() {
    try {
      const raw = localStorage.getItem('vue-desktop:icloud')
      if (!raw) return
      
      const data = JSON.parse(raw)
      if (data.files) {
        // 恢复日期对象
        files.value = data.files.map((f: any) => ({
          ...f,
          modifiedTime: new Date(f.modifiedTime)
        }))
      }
      if (data.viewMode) viewMode.value = data.viewMode
      if (data.storageUsed) storageUsed.value = data.storageUsed
      if (data.storageTotal) storageTotal.value = data.storageTotal
    } catch (_) {
      // 忽略错误
    }
  }

  // 清除缓存
  function clearICloudCache() {
    files.value = []
    currentPath.value = ['iCloud Drive']
    viewMode.value = 'grid'
    storageUsed.value = 0
    storageTotal.value = 50
    selectedFiles.value = []
    searchQuery.value = ''
    
    try {
      localStorage.removeItem('vue-desktop:icloud')
    } catch (_) {
      // 忽略错误
    }
  }

  // 初始化加载
  loadFromStorage()

  return {
    files,
    currentPath,
    viewMode,
    storageUsed,
    storageTotal,
    selectedFiles,
    searchQuery,
    addFile,
    deleteFile,
    renameFile,
    toggleFavorite,
    toggleShare,
    setViewMode,
    selectFile,
    deselectFile,
    clearSelection,
    formatFileSize,
    saveToStorage,
    loadFromStorage,
    clearICloudCache,
  }
})

